package com.example.demo.serviceImpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.bean.SongBean;
import com.example.demo.mapper.SongMapper;
import com.example.demo.service.SongService;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SongServiceImpl implements SongService {
    @Autowired
    private SongMapper songMapper;

    @Override
    public SongBean findSong(String rid){
        return songMapper.findSong(rid);
    }

    @Override
    public boolean addSong(SongBean songBean){
        return songMapper.addSong(songBean)>0?true:false;
    }

    //在线搜索歌曲
    @Override
    public Map<String,Object> searchSongs(String key, String pn, String rn){
        //获取搜索结果总数
        String total="";
        //返回结果
        Map<String,Object> resultMap = new HashMap<>();
        //获取http服务端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //参数
        StringBuffer params = new StringBuffer();
        params.append("pn="+pn);
        params.append("&rn="+rn);
        params.append("&key="+key);
        //创建Get请求
        HttpGet httpGet = new HttpGet("http://www.kuwo.cn/api/www/search/searchMusicBykeyWord"+"?"+params);
        //响应模型
        CloseableHttpResponse response = null;
        //搜索结果
        JSONArray list = new JSONArray();

        //JSON对象
        JSONObject result = null;
        try{
            //配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(2000)
                    .setConnectionRequestTimeout(2000)
                    .setSocketTimeout(5000)
                    .setRedirectsEnabled(true).build();
            //将配置信息应用到Get请求里面。
            httpGet.setConfig(requestConfig);
            //伪装请求头
            httpGet.addHeader("csrf","0FRWVXK2YKZ6");
            httpGet.addHeader("Referer","http://www.kuwo.cn/search/list?key=");
            httpGet.addHeader("Cookie","kw_token=0FRWVXK2YKZ6");
            //从Http服务端发起Get请求。
            response = httpClient.execute(httpGet);
            //从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为："+response.getStatusLine());
            if(responseEntity != null){
                String res = EntityUtils.toString(responseEntity,"UTF-8");
                //System.out.println("响应内容为："+ res);
                if(res==null){
                    return null;
                }
                //字符串转JSON对象
                result = JSONObject.parseObject(res);
                //System.out.println(result.getJSONObject("data").getJSONArray("list"));
                //从JSON对象获取数据。
                list = result.getJSONObject("data").getJSONArray("list");
                total = result.getJSONObject("data").get("total").toString();
                System.out.println("查询结果(共"+total+")：");
                for(int i=0;i<list.size();i++){
                    JSONObject name = list.getJSONObject(i);
                    System.out.print(name.get("name")+"，");
                }
                System.out.println("");
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            try{
                if (httpClient != null){
                    httpClient.close();
                }
                if(response != null){
                    response.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        List<SongBean> searchResult =new ArrayList<>();
        if(list.size()<1){
            return null;
        }else {
            System.out.println("用户尝试搜索结果中已经存在的部分：");
            for(int i=0;i<list.size();i++){
                SongBean songBean = new SongBean();
                JSONObject res = list.getJSONObject(i);
                songBean.setName(res.getString("name"));
                songBean.setArtist(res.getString("artist"));
                songBean.setRid(res.getString("rid"));
                songBean.setArtistid(res.getString("artistid"));
                songBean.setPic(res.getString("pic"));
                songBean.setAlbum(res.getString("album"));
                songBean.setSongtime(res.getString("songTimeMinutes"));
                if(songMapper.findSong(songBean.getRid())!=null) {
                    System.out.print(songBean.getName()+",");
                    songBean.setSid(songMapper.findSong(songBean.getRid()).getSid());
                    searchResult.add(songBean);
                }else {
                    if(songMapper.addSong(songBean)>0){
                        songBean.setSid(songMapper.findSong(songBean.getRid()).getSid());
                        searchResult.add(songBean);
                    }else {
                        System.out.println(songBean.getName()+"，添加歌曲失败");
                    }
                }
            }
        }
        resultMap.put("total",total);
        System.out.println("");
        resultMap.put("data",searchResult);
        return resultMap  ;
    }

    //获取播放链接
    @Override
    public String getSongPath(String rid){
        //获取http服务端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //参数
        StringBuffer params = new StringBuffer();
        try{
            params.append("format="+ URLEncoder.encode("mp3","utf-8"));
            params.append("&rid="+rid);
            params.append("&response=url");
            params.append("&type=convert_url3");
            params.append("&br=512kmp3");
            params.append("&from=web");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        //创建Get请求
        HttpGet httpGet = new HttpGet("http://www.kuwo.cn/url"+"?"+params);
        //响应模型
        CloseableHttpResponse response = null;
        //JSON对象
        JSONObject result = null;

        //歌曲地址
        String songPath ="";

        try{
            //配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(2000)
                    .setConnectionRequestTimeout(2000)
                    .setSocketTimeout(5000)
                    .setCookieSpec(CookieSpecs.STANDARD)
                    .setRedirectsEnabled(true).build();
            //将配置信息应用到Get请求里面。
            httpGet.setConfig(requestConfig);

            //伪装请求头
            httpGet.addHeader("csrf","0FRWVXK2YKZ6");
            httpGet.addHeader("Referer","http://www.kuwo.cn/search/list?key=");
            httpGet.addHeader("Cookie","kw_token=0FRWVXK2YKZ6");
            //有客户端发起Get请求。
            response = httpClient.execute(httpGet);
            //从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            //System.out.println("响应状态为："+response.getStatusLine());
            if(responseEntity != null){
                songPath = EntityUtils.toString(responseEntity,"UTF-8");
                //System.out.println("响应内容为："+ res);
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            try{
                if (httpClient != null){
                    httpClient.close();
                }
                if(response != null){
                    response.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        if(songPath.length()<1){
            return null;
        }else {
            JSONObject sPath = JSONObject.parseObject(songPath);
            return sPath.getString("url");
        }
    }
}
